<?php

if (!defined('IN_SYS'))
    exit('Access Denied');

class importbaidu_controller extends admincp {

    public $error = [];

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        require self::tpl("importbaidu");
    }

    public function uploads() {
        $time = time();
        $config = array(
            "pathFormat" => "/data/temp/{time}{rand:6}",
            "maxSize" => 2048000,
            "allowFiles" => array('.xls', '.xlsx'),
        );
        $up = new uploader('file', $config, 'upload');
        $data = $up->getFileInfo();
        $suc = 0;
        $error = 0;
        if (!empty($data) && $data['state'] == "SUCCESS") {
            $file = ROOT . $data['url'];
            if (is_file($file)) {
                $excel = new PHPExcel();
                try {
                    $inputFileType = PHPExcel_IOFactory::identify($file);
                    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                    $objPHPExcel = $objReader->load($file);
                } catch (Exception $e) {
                    die("加载文件发生错误：" . $e->getMessage());
                }

                // 确定要读取的sheet，什么是sheet，看excel的右下角，真的不懂去百度吧
                $sheet = $objPHPExcel->getSheet(0);
                $highestRow = $sheet->getHighestRow();
                $highestColumn = $sheet->getHighestColumn();

                // 获取一行的数据
                for ($row = 2; $row <= $highestRow; $row++) {
                    // Read a row of data into an array
                    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
                    //这里得到的rowData都是一行的数据，得到数据后自行处理，我们这里只打出来看看效果
                    $res = $this->checkdata($rowData, $row);
                    if ($res) {
                        mredis::lPush('queue_improtbaidu_yuming', json_encode($res));
                        $suc++;
                    } else {
                        $error++;
                    }
                }
                $this->respone_json(array('suc' => $suc, 'error' => $error, 'error_tips' => $this->error));
            } else {
                $this->respone_json('找不到文件');
            }
        } else {
            $this->respone_json($data['state']);
        }
    }

    protected function checkdata($data, $row) {
        if (empty($data[0])) {
            return false;
        }
        $res = $data[0];
        $result = [];
        if (!empty($res[0]) && $this->checkWebSite($res[0], $row)) {
            $result['name'] = $res[0];
        } else {
            $this->error[$row][] = '没找到域名';
            return false;
        }
        if (!empty($res[1])) {
            $result['baidu_token'] = trim($res[1]);
        } else {
            $this->error[$row][] = '网站名称不能为空';
            return false;
        }
        return $result;
    }

    protected function checkWebSite($webSite, $row) {
        $res = parse_url($webSite);
        if (empty($webSite) || $res['path'] != $webSite) {
            $this->error[$row][] = '域名格式不符，请检查';
            return false;
        }
        $has_site = db::getField("select count(*) from `yuming` where name='$webSite'");
        if ($has_site >0) {
            return true;
        }else {
            $this->error[$row][] = '域名不存在，跳过导入';
            return false;
        }
        
    }

    //任务处理中心
    public function doing() {
        header('X-Accel-Buffering: no'); //关闭输出缓存
        ob_end_flush();
        ob_implicit_flush(true);
        $hasdone = 0;
        $count = 0;
        for ($i = 0; $i <= 1000; $i++) {
            $data = mredis::rPop('queue_improtbaidu_yuming');
            if (!empty($data)) {
                try {
                    $data = json_decode($data, true);
                    $res = $this->do_data($data);
                    if ($res) {
                        $count++;
                    }
                } catch (Exception $ex) {
                    continue;
                }
                mac_echo("已成功处理" . $count . "条。");
            } else {
                $hasdone = 1;
                break;
            }
        }
        if ($hasdone == 1) {
            mac_echo('已全部处理完成');
            sleep(3);
            self::redirect("?m=yuming&a=index");
        } else {
            mac_echo('继续进行处理');
            sleep(1);
            header('X-Accel-Buffering: yes'); //关闭输出缓存
            self::redirect("?m=seo&a=importbaidu&doing");
        }
    }

    public function test() {
        $data = db::table_exist('words');
    }

    protected function do_data($data) {
        try {
            pdodb::startTrans(); //开启事务
            if ($this->checkWebSite($data['name'], 1)) {
                $template = ['defaultBlack', 'defaultGray', 'defaultRed'];
                $ran_key = array_rand($template, 1);
                $yuming = pdodb::getOne('yuming', ['name' => $data['name']], '*');
                if(empty($yuming)) {
                    return false;
                }
                $yuming_id = $yuming['id'];
                $seoconfig = pdodb::getOne('seoconfig', ['yuming_id' => $yuming_id], '*');
                if(empty($seoconfig)) {
                    $insert['seoTitle']=1;
                    $insert['seoTitlex']=1;
                    $insert['seoWordNum']=1;
                    $insert['seoWordScale']=100;
                    $insert['baidu_token']=$data['baidu_token'];
                    $insert['yuming_id']=$yuming_id;
                    pdodb::insert('seoconfig',$insert);
                }else {
                     pdodb::update('seoconfig', ['baidu_token'=>$data['baidu_token']],['id'=>$seoconfig['id']]);
                }
                pdodb::commit();
                return true;
            }
        } catch (Exception $ex) {
            logging_run($ex->getMessage(), 'error');
            pdodb::rollback();
            return false;
        }
    }

}
